import React, { Component } from "react";

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        name: "zhangsan",
      },
      {
        id: 2,
        name: "kunkun",
      },
    ],
    textValue: "",
  };

  handChange = (e) => {
    this.setState({
      textValue: e.target.value,
    });
  };

  add = () => {
    if (this.state.textValue) {
      this.setState((prevState) => ({
        list: [
          ...prevState.list,
          { name: this.state.textValue, id: new Date().getTime() },
        ],
        textValue: "",
      }));
    }
  };

  remove = (id) => () => {
    // console.log("removed", id);
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };

  render() {
    return (
      <>
        <h2>todolist</h2>
        <input
          type="text"
          value={this.state.textValue}
          onChange={this.handChange}
        />
        <button onClick={this.add}>添加</button>

        <ul>
          {this.state.list.map((item) => (
            <li key={item.id}>
              {item.name} - <button onClick={this.remove(item.id)}>删除</button>
            </li>
          ))}
        </ul>
      </>
    );
  }
}

export default App;
